//
//  UserAuthMiddleware.swift
//  App
//
//  Created by 汤泽川 on 2019/3/28.
//

import Foundation
import Vapor
import FluentMySQL

public final class UserAuthMiddleware : Middleware {
    public func respond(to request: Request, chainingTo next: Responder) throws -> EventLoopFuture<Response> {
        return try request.content.decode(RequestModel<EmptyData>.self).flatMap({
            content in
            guard let accessToken = content.accessToken else {
                throw APIError.illegalAccessTokenError
            }
            return UserAccessToken.query(on: request).filter(\.accessToken == accessToken).first().flatMap({
                storeToken in
                guard let storeToken = storeToken else {
                    throw APIError.validateAccessTokenError
                }
                if accessToken != storeToken.accessToken {
                    throw APIError.validateAccessTokenError
                }
                return try next.respond(to: request)
            }).catchFlatMap({
                error in
                throw error
            })
        }).catchFlatMap({
            error in
            throw error
        })
    }
}
